<template>
	<view class="edit-popup">
		<uv-popup ref="popup" type="center" :close-on-click-overlay="false" bg-color="#212329">
			<view class="content" style="padding: 50px;">
				<view class="hd uv-flex-row">
					<uv-button text="返回" @click="close"></uv-button>
				</view>
				<view class="bd uv-flex-row">
					<view class="list">
						<view class="category">
							<view class="item uv-flex-row" v-for="(item,index) in chapterItem.categoryList" :key="index">
								<uv-avatar :src="item.logo" size="50px"></uv-avatar>
								<uv-text :text="item.name" color="#fff"></uv-text>
							</view>
							<view class="item">
								<uv-button text="添加星球" @click="addcategory"></uv-button>
							</view>
						</view>
						<view class="uv-flex-row" style="padding: 10px 0 30px;">
							<uv-button :text="showSort?'取消调整':'调节顺序'" :throttle-time="200" style="margin: 0 5px;" @click="sort"></uv-button>
							<template v-if="!showSort">
								<uv-button text="新建组别" :throttle-time="200" style="margin: 0 5px;" @click="createGroup"></uv-button>
								<uv-button text="新建课程" :throttle-time="200" style="margin: 0 5px;" @click="createCourse"></uv-button>
							</template>
						</view>
						<select-list :list="courseList" :show-sort="showSort" @sort-end="sortChange" @select="select" @clickItem="clickItem" @more="clickMenu" @add="createCourse"></select-list>
					</view>
					<view class="detail">
					</view>
				</view>
			</view>
		</uv-popup>
		<fixed-menu ref="menu">
			<uv-button text="重命名组别" @click="resetName('courseGroupName')" v-if="menuContent.type == 'GROUP'"></uv-button>
			<uv-button text="重命名" @click="resetName('name')" v-if="menuContent.type == 'COURSE'"></uv-button>
			<uv-button text="多选"></uv-button>
			<uv-button text="调整课程顺序" @click="showSort=true"></uv-button>
			<uv-button text="删除" type="error" @click="remove"></uv-button>
		</fixed-menu>
	</view>
	<input-popup @confirm="confirm" :value="inputText" :title="menuContent.type == 'GROUP'?'组别名称':'课程名称'" :placeholder="menuContent.clickType == 'GROUP'?'请输入组别名称':'请输入课程名称'" ref="namePopupRef" />
</template>
<script setup>
	import { reactive, ref, getCurrentInstance, computed, defineComponent, watchEffect, nextTick } from 'vue';
	import { customCourseCreate, customCourseSort } from '@/common/api/course.js'
	const { ctx } = getCurrentInstance();
	const db = uniCloud.database();
	let chapterItem = reactive({});
	const courseList = ref([]);
	const popup = ref(null);
	const menu = ref(null);
	const namePopupRef = ref(null);
	const menuContent = ref({});
	let checked = reactive({});
	const showSort = ref(false)
	const myCharacterId = computed(() => {
		return getApp().globalData.dzcharacter?.character?.characterId;
	})
	const categoryItem = computed(() => {
		return chapterItem.categoryList[0];
	})
	const inputText = computed(() => {
		return menuContent.value.type == 'GROUP' ? menuContent.value.courseGroupName : menuContent.value.name;
	})
	watchEffect(() => {
		console.log(checked.courseId)
		if (checked.courseId) {
			console.log('请求详情数据')
		}
	})

	function sort() {
		showSort.value = !showSort.value;
	}

	function select() {}

	function clickItem(v) {
		checked = Object.assign({}, v);
	}
	// 根据category星球获取课程的组
	async function getCourseList() {
		const { category } = categoryItem.value;
		const categoryTemp = db.collection('a-dz-category-list-custom').where(`category == "${category}"`).getTemp();
		const courseTemp = db.collection('a-dz-course-list-custom').where(`category == "${category}"`).orderBy('courseOrder asc').getTemp();
		let { result } = await db.collection(categoryTemp, courseTemp).get();
		if (result.data.length) {
			const list = result.data[0].category['a-dz-course-list-custom'];
			courseList.value = []
			nextTick(()=>{
				courseList.value = getGroup(list);
				console.log('分组获得数据：', courseList.value)
			})
		} else {
			courseList.value = [];
		}
	}
	async function clickMenu({ item, type, rect }) {
		const { left, top, height, width } = rect;
		menu.value.show(left + width / 2, top + height / 2);
		menuContent.value = item;
	}
	async function remove() {
		uni.showLoading({
			title: '删除中'
		})
		const { courseId, courseGroup } = menuContent.value;
		const { uid } = uniCloud.getCurrentUserInfo();
		console.log('删除中删除中===》',courseId, courseGroup)
		const where = courseId ? `uid == "${uid}" && courseId == ${courseId}` : `uid == "${uid}" && courseGroup == "${courseGroup}"`;
		// 删除自定义课程
		await db.collection('a-dz-course-list-custom').where(where).remove();
		getCourseList();
		uni.hideLoading();
	}
	async function createCourse(item) {
		uni.showLoading({
			title: '请求中'
		})
		const { uid } = uniCloud.getCurrentUserInfo();
		const characterId = myCharacterId.value;
		const { chapter } = chapterItem;
		const { category } = categoryItem.value;
		const courseGroup = item?.courseGroup ? item.courseGroup : checked.courseGroup;
		const _courseList = courseList.value.find(item => item.courseGroup == courseGroup);
		const courseGroupName = _courseList?.courseGroupName;
		console.log('courseGroupNamecourseGroupName', courseGroupName)
		await customCourseCreate({
			characterId,
			uid,
			chapter,
			category,
			courseGroup,
			courseGroupName
		})
		getCourseList();
		uni.hideLoading();
	}
	// 排序
	async function sortChange(list) {
		const { uid } = uniCloud.getCurrentUserInfo();
		customCourseSort({
			list,
			uid
		}).then(res=>{
			getCourseList();
		})
	}
	async function createGroup() {
		uni.showLoading({
			title: '请求中'
		})
		const { uid } = uniCloud.getCurrentUserInfo();
		const characterId = myCharacterId.value;
		const { chapter } = chapterItem;
		const { category } = categoryItem.value;
		await customCourseCreate({
			characterId,
			uid,
			chapter,
			category
		})
		getCourseList();
		uni.hideLoading();
	}

	function resetName(type) {
		namePopupRef.value.open(type);
	}
	async function confirm(res) {
		const { value, type } = res;
		const { uid } = uniCloud.getCurrentUserInfo();
		const { courseId, courseGroup, name } = menuContent.value;
		uni.showLoading({
			title: '修改中'
		})
		console.log('修改中修改中===》',courseId, courseGroup, name)
		const where = type == 'courseGroupName' ? `uid == "${uid}" && courseGroup == "${courseGroup}"` : `uid == "${uid}" && courseId == ${courseId} && name == "${name}"`;
		await db.collection('a-dz-course-list-custom').where(where).update({
			[type]: value
		});
		getCourseList();
		uni.hideLoading();
	}
	async function open(item) {
		chapterItem = Object.assign(chapterItem, item);
		console.log('chapterItem===>', chapterItem)
		popup.value.open();
		getCourseList();
	}

	function close() {
		popup.value.close();
	}

	function addcategory() {
		uni.showModal({
			content: '开通机构版才能放开限制'
		})
	}

	function getGroup(arr) {
		const groupedCourses = arr.reduce((acc, course) => {
			// 查找是否已存在该courseGroup和courseGroupName的组合
			const existingGroup = acc.find(group => group.courseGroup === course.courseGroup && group.courseGroupName === course.courseGroupName);
			if (existingGroup) {
				// 如果存在，则添加课程到该分组
				existingGroup.courses.push(course);
			} else {
				// 如果不存在，则创建新的分组
				acc.push({
					courseGroup: course.courseGroup,
					courseGroupName: course.courseGroupName,
					courses: [course]
				});
			}
			return acc;
		}, []);
		return groupedCourses;
	}
	defineExpose({
		open
	})
</script>
<style>
	.edit-popup>>>.uv-popup .uv-popup__content {
		width: 100%;
		height: 100%;
	}
</style>
<style scoped lang="scss">
	.content {
		// width: 100%;
		// height: 100%;
	}
</style>